package user

import (
	ruleService "github.com/crazyhl/gopermission/service/rule"
	"github.com/gofiber/fiber/v2"
	"go-fiber-demo/models"
	"go-fiber-demo/pkg"
)

// 角色绑定用户
func AttachRole(ctx *fiber.Ctx) error {
	uid := ctx.Params("id", "")
	gormDb := pkg.GetConfig().GormDb
	user := new(models.User)

	gormDb.Where("id = ?", uid).First(&user)

	response := new(pkg.Response)
	if user.ID == 0 {
		response.Status = -1
		response.Message = "用户不存在"
		return ctx.JSON(response)
	}
	// 接收传入的 permissions id ，然后替换关联
	form, err := ctx.MultipartForm()
	if err != nil {
		response.Status = -2
		response.Message = err.Error()
		return ctx.JSON(response)
	}
	ruleIds := form.Value["rules"]
	// 通过id 查找权限
	rules := ruleService.FindByIdsString(ruleIds)

	err = gormDb.Model(&user).Association("Rules").Replace(rules)

	if err != nil {
		response.Status = -3
		response.Message = err.Error()
		return ctx.JSON(response)
	}

	response.Message = "关联成功"

	return ctx.JSON(response)
}
